# -*- coding: utf-8 -*-

import os
import sqlite3

    
def readFileDir(filePath):


    conn = sqlite3.connect("db.sqlite3")
    cu = conn.cursor()
    cu.execute("delete from autocases_testcases")
    conn.commit()

    data = [{'name' : filePath, 'id' : 1, 'pId' : 0, 'isParent' : 1, 'fileUrl' : ''}]

    cid = 2
    for parent, dirnames, filenames in os.walk(filePath):

        if parent.find("svn") != -1:
            continue

        for dirname in dirnames:
            path = os.path.join(parent, dirname)

            if path.find("svn") != -1:
                continue

            parent_id = -1
            for item in data:
                if item['name'] == parent:
                    parent_id = item['id']

            if int(parent_id) >= 0:
                pid = parent_id
            else:
                pid = int(data[-1]['pid']) +1
                
            # print 'name -> ', path
            data.append({'name' : path, 'id': cid, 'pId': pid, 'isParent' : 1, 'fileUrl' : ''})
            cid += 1

        for filename in filenames:
            path = os.path.join(parent, filename)

            if not path.endswith('.txt'):
                continue

            parent_id = -1
            for item in data:
                if item['name'] == parent:
                    parent_id = item['id']

            if int(parent_id) >= 0:
                pid = parent_id
            else:
                pid = int(data[-1]['pid']) +1

            data.append({'name' : path, 'id': cid, 'pId': pid, 'isParent' : 0, 'fileUrl' : path})
            cid += 1

    for item in data:
        # item['name'] = os.path.basename(item['name']).decode('gbk').encode('utf-8')
        # item['fileUrl'] = item['fileUrl'].decode('gbk').encode('utf-8')
        # print item['name'], item['fileUrl']

        item['name'] = os.path.basename(item['name'])
        print item['name'], item['fileUrl']

        cu.execute("insert into autocases_testcases(id, pId, name, isParent, fileUrl) values(%d, %d, '%s', %d, '%s')" % (int(item['id']), int(item['pId']), item['name'], item['isParent'], item['fileUrl']))

    conn.commit()
    cu.close()
    conn.close()
                       
                       
                       
if __name__ == '__main__':
    
    print 'starting...'
    path = r'/root/testbed/SKS_product/Testcase'
    readFileDir(path)
    print 'OK'